<template>
  <el-dialog v-model="visible" :close-on-click-modal="false" :close-on-press-escape="false" style="top: -10%;">
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <div :id="titleId" style="font-size: 18px;">{{ dataForm.seriesName + '系列' }}</div>
        <div :style="{ color: dataForm.ifValid === 0 ? 'red' : 'gray' }"
          style="margin-left: 10px;margin-top: 3px;font-size: 13px;">
          ({{ dataForm.ifValid === 0 ? '在售' : '停产' }})
        </div>
      </div>
    </template>
    <el-form :model="dataForm" ref="dataFormRef">
      <div style="display:flex;justify-content: space-around;">
        <el-form-item>
          <div>品牌名称:</div>
          <el-text>{{ dataForm.brandName }}</el-text>
        </el-form-item>
        <el-form-item>
          <div>产品编号:</div>
          <el-text>{{ dataForm.seriesCode }}</el-text>
        </el-form-item>
        <el-form-item>
          <el-text>{{ dataForm.className }}</el-text>
        </el-form-item>
      </div>
      <div v-show="showFlag">
        <el-tabs v-show="showFlag" v-model="activeTab" style="margin-left: 50px;">
          <el-tab-pane label="型号信息" name="tab1">
            <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs">
              <el-tab-pane v-for="(item, index) in editableTabs" :key="item.name" :label="item.productName || '未命名型号'"
                :name="item.name">
                <el-form-item label-width="0">
                  <div style="font-weight: 600;"><span style="color: red;">*</span>产品图片/视频</div>
                </el-form-item>
                <!-- 图片/视频上传区域（每个tab独立文件列表） -->
                <el-form-item label-width="0">
                  <div class="image-upload-container" style="width: 684px;">
                    <div class="upload-tip">
                      <span style="color: rgba(56, 56, 56, 1);">产品图片/视频上传</span><br>
                      <span style="color: rgba(168, 171, 178, 1);">
                        仅支持上传图片、视频，最多可上传6张与1个视频，
                        已上传 1/6图片、
                        0/1视频，拖拽图片可调整顺序
                      </span>
                    </div>

                    <!-- 图片上传组件（绑定当前tab的imageFiles） -->
                    <div class="image-upload-section" v-if="item.banarImg && item.banarImg.trim() !== ''">
                      <div class="image-upload-label">图片：</div>
                      <div style="display: flex;flex-wrap: wrap;">
                        <div class="upload-box" v-for="(imgUrl, index) in item.banarImg!.split(',')" :key="index"
                          style="margin-right: 20px;">
                          <img :src="imgUrl" class="uploaded-image" />
                        </div>
                      </div>
                    </div>

                    <!-- 视频上传组件（绑定当前tab的videoFiles） -->
                    <div class="video-upload-section" v-if="item.productVideoUrl && item.productVideoUrl.trim() !== ''">
                      <div class="video-upload-label">视频：</div>
                      <div class="upload-box">
                        <video :src="item.productVideoUrl" class="uploaded-image" controls></video>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label-width="0">
                  <div style="display: flex;">
                    <div style="font-weight: 600;margin-right: 10px;font-size:14px;">参数信息</div>
                    <div style="color: rgba(22, 119, 255, 1); font-size: 12px;" @click="toggleParameterInfo">
                      {{ isParameterInfoCollapsed ? '展开' : '一键收起' }}
                    </div>
                  </div>
                </el-form-item>
                <!-- 属性组示例（假设每个tab有独立的属性组数据） -->
                <div v-for="(group, groupIndex) in item.productAttrGroupList" :key="groupIndex"
                  style="display: flex; align-items: center;" v-show="!isParameterInfoCollapsed">
                  <div class="attribute-group">
                    <div style="font-size: 14px; font-weight: 600;margin-bottom: 30px;">{{ group.groupName }}</div>
                    <el-form-item v-for="(itemInput, inputIndex) in group.productAttrs" :key="inputIndex"
                      style="margin-bottom: 20px;">
                      <div style="width: 96px;">{{ itemInput.attrName }}</div>
                      <el-text>{{ itemInput.attrValue }}</el-text>
                    </el-form-item>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
          <el-tab-pane label="基础信息" name="tab2">
            <el-form label-width="110px" style="margin-top: 20px;margin-left: -32px;" :model="dataForm"
              :ref="dataFormRef2">
              <el-form-item label="产品详情" prop="name">
                <div class="image-upload-container" v-if="uploadedFiles.length > 0">
                  <div class="upload-tip">
                    <!-- <div class="tip-text">最多可上传10张，已上传 {{ uploadedFiles.length }}/10
                    </div> -->
                  </div>
                  <div style="display: flex;flex-wrap: wrap;">
                    <div class="upload-box" v-for="(item, index) in uploadedFiles" :key="index"
                      style="margin-right: 20px;">
                      <img :src="item" class="uploaded-image" />
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-show="!showFlag" style="margin-left: 50px">
        <div style="display: flex; align-items: center; padding: 0 20px;">
          <div style="flex: 0 0 200px;"><span style="color:red">*</span>请选择上架的型号</div>
          <div style="flex: 0 0 300px; text-align: center;">是否报价</div>
          <div style="flex: 1; text-align: center;"><span style="color:red">*</span>请输入型号价格</div>
        </div>
        <div v-for="item in productQuotationList" :key="item.id" class="money" style="display: flex; align-items: center; padding: 0 20px; margin-top: 20px;">
          <div style="flex: 0 0 200px;">
            <el-checkbox v-model="item.checked" @change="handleCheckChange(item)">
              {{ item.productName }}
            </el-checkbox>
          </div>
          <!-- 是否报价开关，只在选中时显示 -->
          <div style="flex: 0 0 300px; display: flex; justify-content: center;">
            <el-switch
              v-if="item.checked"
              v-model="item.quoted"
              :active-value="1"
              :inactive-value="0"
              @change="handleQuotedChange(item)"
            />
          </div>
          <!-- <el-checkbox :checked="!!item.quotation">{{ item.productName }}</el-checkbox> -->
          <div style="flex: 1; display: flex; justify-content: center;">
            <el-input
              v-model="item.quotation"
              placeholder="请输入金额"
              style="width: 156px;"
              :disabled="!item.checked || item.quoted === 0"
              @blur="validatePrice(item)"
              @input="formatPrice(item)"
            >
            </el-input>
          </div>
          <!-- <el-input v-model="item.quotation" placeholder="请输入金额" style="width: 156px;margin-left: 81px;"></el-input> -->
        </div>
      </div>
    </el-form>

    <template v-slot:footer>
      <el-button v-show="showFlag" @click="showFlag = false" type="primary">下一步</el-button>
      <div v-show="!showFlag">
        <el-button class="quxiao" @click="showFlag = true">上一步</el-button>
        <el-button @click="dataFormSubmitHandle()" :disabled="!hasSelectedProduct"
          style="background: rgba(22, 119, 255, 1);color: #fff;width: 100px;border-radius: 5px;">
          一键报价
        </el-button>
        <!-- <el-button @click="dataFormSubmitHandle()"
          style="background: rgba(22, 119, 255, 1);color: #fff;width: 100px;border-radius: 5px;">一键报价</el-button> -->
      </div>
    </template>

  </el-dialog>

</template>

<script lang="ts" setup>
import { computed, nextTick, reactive, ref, toRefs, watch } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import app from "@/constants/app";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const dataFormRef2 = ref();
const showFlag = ref(true);
const dataForm = reactive({
  seriesId: "",
  seriesCode: "",
  seriesName: "",
  className: "",
  brandName: "",
  mainImages: "",
  imgUrls: "", // 改为字符串类型，存储逗号分隔的URL
  productList: [] as Product[],
  ifValid: null // 新增属性
});

interface Product {
  id: number;
  name: string;
  productName: string;
  banarImg: string;
  productVideoUrl: string;
  productAttrGroupList: {
    id: number;
    groupName: string;
    productAttrs: {
      id: number;
      attrName: string;
      attrValue: string
    }[]
  }[];
}

const productQuotationList = ref<ProductQuotation[]>([]); // 产品报价列表
interface ProductQuotation {
  id: number;
  productId: number; // 关联产品ID
  productName: string;
  quotation: string; // 报价金额（字符串形式，如"100.00"）
  checked: boolean;  // 是否选中
  quoted: number;    // 是否报价（1=报价，0=不报价）
}

const getProductQuotationList = (id: number) => {
  baseService.get("/noc/productuserquotation/getProductUserQuotationBySeriesId", { seriesId: id }).then((res) => {
    if (res.code === 0 && res.data) {
      productQuotationList.value = res.data.map((item: any) => ({
        ...item,
        checked: item.quoted != null && item.quoted >= 0,
        quotation: item.quotation ? parseFloat(item.quotation).toFixed(2) : '',
        quoted: item.quoted
      }));
    }
  });
};



// 处理勾选变化
const handleCheckChange = (item: any) => {
  if (!item.checked) {
    item.quotation = ''; // 取消勾选时清空报价
    item.quoted = 1; // 重置为默认开启状态
  }
};

// 处理是否报价开关变化
const handleQuotedChange = (item: any) => {
  if (item.quoted === 0) {
    item.quotation = ''; // 关闭报价开关时清空价格
  }
};

// 修改计算属性
const hasSelectedProduct = computed(() => {
  return productQuotationList.value.some(item => item.checked);

});

const formatPrice = (item: any) => {
  if (item.quotation) {
    // 只允许数字和小数点
    item.quotation = item.quotation.replace(/[^\d.]/g, '');
    // 确保只有一个小数点
    const parts = item.quotation.split('.');
    if (parts.length > 2) {
      item.quotation = parts[0] + '.' + parts.slice(1).join('');
    }
    // 限制小数点后两位
    if (parts.length === 2) {
      item.quotation = parts[0] + '.' + parts[1].slice(0, 2);
    }
  }
};

// 验证价格
const validatePrice = (item: any) => {
  if (item.quotation) {
    const num = parseFloat(item.quotation);
    if (isNaN(num) || num <= 0) {
      ElMessage.error('请输入大于0的数字');
      item.quotation = '';
    } else {
      // 格式化为两位小数
      item.quotation = num.toFixed(2);
    }
  }
};


//一键收起展示
const isParameterInfoCollapsed = ref(false)
const toggleParameterInfo = () => {
  isParameterInfoCollapsed.value = !isParameterInfoCollapsed.value;
};

const uploadUrl = `${app.api}/sys/oss/upload`;

const editableTabs = ref<Product[]>([]); // 响应式tab列表
const editableTabsValue = ref<string>(''); // 当前激活的tab名称
let tabIndex = 0; // 用于生成唯一标识
const uploadedFiles = ref<string[]>([]);
const init = (id?: number, ifValid?: any) => {
  visible.value = true;
  dataForm.seriesId = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  if (dataFormRef2.value) {
    dataFormRef2.value.resetFields();
  }
  if (id) {
    dataForm.seriesId = id.toString();
    getSeries(id);
    getProductQuotationList(id)
  }
  if (ifValid !== undefined) {
    dataForm.ifValid = ifValid; // 存储传递过来的 ifValid
  }
};

const handleImageSuccess = (res: any, fileList: any[], item: Product) => {
  if (res.code !== 0) {
    ElMessage.error(res.msg || '上传失败');
    return;
  }
}

const getSeries = (id: number) => {
  baseService.get("/noc/productseries/info/" + id).then((res) => {
    if (res.code === 0 && res.data) {
      Object.assign(dataForm, res.data);
      console.log(dataForm);
      // 如果有已上传的图片，初始化uploadedFiles
      if (dataForm.imgUrls) {
        uploadedFiles.value = dataForm.imgUrls.split(',');
      }
      // 确保 productAttrGroupList 是一个数组
      const productList = Array.isArray(res.data.productList) ? res.data.productList : [];
      console.log(productList);
      editableTabs.value = productList.map((product: any) => {
        console.log(product);
        // 确保 banarImg 是字符串，否则设为空数组
        // 确保 productAttrGroupList 是一个数组
        const attrGroupList = Array.isArray(product.productAttrGroupList) ? product.productAttrGroupList : [];
        return {
          id: product.id,
          seriesId: product.seriesId,
          productName: product.productName,
          name: product.productName,
          banarImg: product.banarImg,
          productVideoUrl: product.productVideoUrl,
          productAttrGroupList: attrGroupList.map((productAttrGroup: any) => {
            // 确保 productAttrs 是一个数组
            const attrs = Array.isArray(productAttrGroup.productAttrs) ? productAttrGroup.productAttrs : [];
            return {
              id: productAttrGroup.id,
              productId: productAttrGroup.productId,
              groupId: productAttrGroup.groupId,
              seriesId: productAttrGroup.seriesId,
              groupName: productAttrGroup.groupName,
              productAttrs: attrs.map((productAttr: any) => ({
                id: productAttr.id,
                productId: productAttr.productId,
                attrId: productAttr.attrId,
                productAttrGroupId: productAttr.productAttrGroupId,
                attrName: productAttr.attrName,
                attrValue: productAttr.attrValue
              }))
            };
          })
        };
      });
      // 如果存在型号数据，默认选中第一个
      console.log(editableTabs.value);
      if (editableTabs.value && editableTabs.value.length > 0) {
        editableTabsValue.value = editableTabs.value[0].name;
      }
    } else {
      ElMessage.error('获取产品系列信息失败');
    }
  });
};




const activeTab = ref('tab1');


// 表单提交
const dataFormSubmitHandle = () => {
  // 获取所有选中的型号
  const checkedItems = productQuotationList.value.filter(item => item.checked);

  if (checkedItems.length === 0) {
    ElMessage.error('请至少选择一个型号');
    return;
  }

  // 验证已选中且开启报价的型号是否填写了有效的金额
  const quotedItems = checkedItems.filter(item => item.quoted === 1);
  const invalidItems = quotedItems.filter(item => {
    const quotationStr = String(item.quotation || '');
    return !quotationStr || !/^\d+(\.\d{1,2})?$/.test(quotationStr) || parseFloat(quotationStr) <= 0;
  });

  if (invalidItems.length > 0) {
    ElMessage.error('已开启报价的型号请输入大于0的数字，最多保留两位小数');
    return;
  }

  // 构建提交数据
  const quotationList = checkedItems.map(item => ({
    ...item,
    quotation: item.quoted === 1 && item.quotation
      ? parseFloat(String(item.quotation)).toFixed(2)
      : null, // 未报价的设为 null
    quoted: item.quoted // 保留是否报价的状态
  }));

  baseService.post("/noc/productuserquotation/saveOrUpdateBatchQuotation", {
    id: dataForm.seriesId,
    quotationList: quotationList
  }).then((res) => {
    ElMessage.success({
      message: t("prompt.success"),
      duration: 500,
      onClose: () => {
        visible.value = false;
        emit("refreshDataList");
      }
    });
  });
};



defineExpose({
  init
});
</script>
<style>
.quxiao {
  border-radius: 5px;
  background: rgba(239, 244, 255, 1);
  color: rgba(22, 119, 255, 1);
  border: 1px solid rgba(22, 119, 255, 1);
}

.form {
  display: flex;
  justify-content: space-between;
}

.image-upload-container {
  width: 511px;
  border: 1px dashed #ccc;
  border-radius: 6px;
  padding: 10px;
}

.model-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.model-item {
  display: flex;
  align-items: center;
}

.model-select {
  padding: 8px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.model-input {
  padding: 8px;
  margin-right: 10px;
  border-radius: 5px;
  width: 156px;
  height: 32px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(199, 199, 199, 1);
}

.model-input:focus {
  border: 0px;
  /* 获得焦点时边框颜色改为蓝色 */
  background: rgba(240, 245, 255, 1);
  color: rgba(22, 119, 255, 1);
  outline: none;
  /* 去除默认的焦点轮廓 */
}

.remove-button {
  padding: 8px 12px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.uploaded-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.attribute-group {
  width: 684px;
  height: 100%;
  padding: 20px;
  border: 1px dashed rgba(31, 31, 31, 0.36);
  border-radius: 18px;
  margin-bottom: 38px;
}

.attribute-group-input {
  width: 492px;
  height: 32px;
}

.money {
  /* 移除原有的 flex 布局样式，因为现在在 HTML 中直接定义 */
}

.quoted-switch-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.quoted-switch-label {
  margin-right: 8px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.parameter {
  width: 96px;
}

.parameter-information {
  display: flex;
  align-items: center;
}

.parameter-title {
  margin-bottom: 20px;
  font-size: 14px;
  font-weight: 600;
}

.my-header {
  display: flex;
}
</style>
